package com.clm.controller;

import com.clm.common.ResultJson;
import com.clm.interceptor.LoginInterceptor;
import com.clm.po.Restaurant;
import com.clm.po.User;
import com.clm.vo.RestaurantVO;
import com.demo.blog.BlogInterceptor;
import com.google.gson.Gson;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserController extends Controller {

    public void login(){
        String name = getPara("name");
        String password = getPara("password");
        if(StringUtils.isBlank(name) || StringUtils.isBlank(password)){
            ResultJson json = new ResultJson();
            json.setCode(1);
            json.setMessage("用户名或密码不能为空!");
            Gson gson = new Gson();
            renderJson(gson.toJson(json));
        }
        int userId = User.dao.login(name,password);
        if(userId > 0){
            setSessionAttr("userName",name);
            forwardAction("/index?id=1");
        }else{
            ResultJson json = new ResultJson();
            json.setCode(-1);
            json.setMessage("登陆失败！用户名或密码错误");
            Gson gson = new Gson();
            renderJson(gson.toJson(json));
        }
    }

    @Before(LoginInterceptor.class)
    public void find(){
        String id = getPara("id");
        if(id == null || "".equals(id.trim())){
            ResultJson json = new ResultJson();
            json.setCode(1);
            json.setMessage("id不能为空!");
            Gson gson = new Gson();
            renderJson(gson.toJson(json));
        }

        User user = User.dao.findById(id);

        ResultJson json = new ResultJson();
        if(user != null){
            json.setCode(0);
            json.setMessage("success");

            Map<String,Object> resultMap = new HashMap<String, Object>();
            for (Map.Entry<String, Object> entry : user.getAttrsEntrySet()) {
                resultMap.put(entry.getKey(),entry.getValue());
            }
            json.setData(resultMap);
        }else{
            json.setCode(-1);
            json.setMessage("faile");
        }
        Gson gson = new Gson();
        renderJson(gson.toJson(json));
    }
}


